<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

if(!defined('TinyFW')) exit('Access denied!');

class tfFormSelect extends tfFormElement {


    private $_options = array();
    private $_multiple = false;

    private $_size = null;
    private $_value = null;


    public function  __construct($name='', $id='', $caption='', $value='', $size='1', $attr_arr = '', $multiple=false) {

        $this->setName($name);
        $this->setId($id);
        $this->setCaption($caption);
        $this->setValue($value);
        $this->setSize($size);
        $this->_multiple = $multiple;
        if(is_array($attr_arr)) {
            $this->setAttr($attr_arr);
        }

    }

    //check if this is the multiple choice select element
    public function isMultiple() {
        return $this->_multiple;
    }

    public function getSize() {
        return $this->_size;
    }

    private function setSize($size) {
        $this->_size = $size;
    }

    //override the setValue function
    public function setValue($value) {
        if(is_array($value)) {
            foreach($value as $v) {
                $this->_value[] = $v;
            }
        } elseif(isset ($value)) {
            $this->_value[] = $value;
        }
    }

    public function addOption($value, $name='') {

        if($name == '') {
            $this->_options[$value] = $value;
        } else {
            $this->_options[$value] = $name;
        }
    }

    public function addOptionArray($options) {
        if(is_array($options)) {
            foreach($options as $k => $v) {
                $this->addOption($k, $v);
            }
        }
    }

    public function getOptions() {
        return $this->_options;
    }

    public function render() {
        $ret = "<select size='" . $this->getSize() . "' " . $this->getAttrStr() . " ";
        if($this->isMultiple()) {
            $ret .= "name='" . $this->getName() . "[]' id='" . $this->getId() . "'  multiple='multiple' >\r\n";
        } else {
            $ret .= "name='" . $this->getName() . "' id='" . $this->getId() . "' >\r\n";
        }

        foreach($this->_options as $value => $name) {
            $ret .= "<option value='" . $value . "' ";
            if(in_array($value, $this->_value)) {
                $ret .= " selected='selected' ";
            }
            $ret .= ">" . $name . "</option>\r\n";
        }
        
        $ret .= "</select>\r\n";

        return $ret;

    }

    /*
    public function  __toString() {
        $this->render();
    }
    */
    
    
}

?>
